package com.highper.common.mq;

import com.alibaba.fastjson.JSONObject;
import com.highper.common.sehcma.ContextHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author ZhangGJ
 * @Date 2022/01/29 10:48
 */
@Slf4j
public class SendMessageRocketMQ {

    @Autowired
    private static RocketMQTemplate rocketMQTemplate;

    public SendMessageRocketMQ(RocketMQTemplate rocketMQTemplate) {
        SendMessageRocketMQ.rocketMQTemplate = rocketMQTemplate;
    }

    public static boolean sendMessage(Object o, String topic) {
        JSONObject messageData = new JSONObject();
        messageData.put("payload", o);
        messageData.put("schema", ContextHandler.getSchema());
        rocketMQTemplate.convertAndSend(topic, messageData);
        log.info("发送消息成功!");
        return Boolean.TRUE;
    }

    public static boolean sendAsyncMessage(Object o, String topic) {
        JSONObject messageData = new JSONObject();
        messageData.put("payload", o);
        messageData.put("schema", ContextHandler.getSchema());
        rocketMQTemplate.asyncSend(topic, messageData, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("async onSuccess SendResult=%s %n", sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("async onException Throwable=%s %n", throwable);
            }
        });
        log.info("发送异步消息成功!");
        return Boolean.TRUE;
    }
    

    public static SendResult sendSyncMessage(Object o, String topic) {
        JSONObject messageData = new JSONObject();
        messageData.put("payload", o);
        messageData.put("schema", ContextHandler.getSchema());
        return rocketMQTemplate.syncSend(topic, o);
    }

    public static boolean sendOneWay(Object o, String topic) {
        JSONObject messageData = new JSONObject();
        messageData.put("payload", o);
        messageData.put("schema", ContextHandler.getSchema());
        rocketMQTemplate.sendOneWay(topic, messageData);
        log.info("发送消息成功!");
        return Boolean.TRUE;
    }
}
